package com.beiming.ndkdemo;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Bitmap2File {

    public static String TAG = "Bitmap2File";

    /**
     * 保存bitmap到本地
     *
     * @param bitmap Bitmap
     */
    public static void saveBitmap(Bitmap bitmap, String path, int taskId) {
        File filePic;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File newFileDir = new File(Environment.getDownloadCacheDirectory(), path);
            if (!newFileDir.exists()) {
                newFileDir.mkdir();
            }
            filePic = new File(newFileDir, taskId + "-" + System.currentTimeMillis() + ".jpg");
            try {
                if (!filePic.exists()) {
                    filePic.getParentFile().mkdirs();
                    filePic.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(filePic);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
                Log.i(TAG, "saveBitmap success: " + filePic.getAbsolutePath());
            } catch (IOException e) {
                Log.e(TAG, "saveBitmap: " + e.getMessage());
                return;
            }
        } else {
            Log.e(TAG, "saveBitmap failure : sdcard not mounted");
        }
    }
}
